import SoundManager, { ClipPlayingInfo } from "../../../core/sound_manager";
import { SubjectComponent } from "../../../core/subject"; 
import CCObject from "../../eggy/cc_game/cc_object";
import CCCharacterBomb from "../game/cc_character_bomb";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CCBomb extends CCObject {
    @property(cc.ParticleSystem)
    pac: cc.ParticleSystem = null;
    @property(cc.Label)
    lbTime: cc.Label = null;

    ownerChar: CCCharacterBomb = null;
    dster: CCCharacterBomb = null;

    isDead = false;
    flying = false;

    _time = 0;
    get time() {
        return this._time;
    }
    set time(val) {
        this._time = val;
        this.lbTime.string = `${this._time.toFixed(0)}`;
    }
    cInfo: ClipPlayingInfo = null;
    protected onLoad(): void {
        this.cInfo = SoundManager.ins.playClip("si", true);
    }
    protected onDestroy(): void {
        if (this.cInfo) {
            SoundManager.ins.stopClip(this.cInfo);
            this.cInfo = null;
        }
    }
    async flyTo(dst: CCCharacterBomb) {
        if (!cc.isValid(this)) {
            return;
        }
        let srcPt = cc.v2(this.node.position);
        let dstPt = cc.v2(dst.node.position);

        srcPt.y += 200;
        dstPt.y += 200;
        let mid = srcPt.lerp(dstPt, 0.5);
        mid.y += 400;

        this.flying = true;
        this.ownerChar = null;
        this.dster = dst;
        cc.Tween.stopAllByTarget(this.node);
        cc.tween(this.node)
            .bezierTo(0.5, srcPt, mid, dstPt)
            .call(async () => {
                dst.grab(this);
                this.ownerChar = dst;
                this.dster = null;
                this.flying = false;
            })
            .start();
    }
    blowup() {
        if (this.isDead) {
            return;
        }
        this.isDead = true;
        this.emit("blowup", this);
        this.node.active = false;
        if (this.cInfo) {
            SoundManager.ins.stopClip(this.cInfo);
            this.cInfo = null;
        }
    }
    protected update(dt: number): void {
        if (!this.isDead) {
            this.time -= dt;
            if (this.time <= 0) {
                this.blowup();
            }
        }
    }
};